/**    
 * @{#} BinglijiaActivity.java Create on 2014-5-29 下午9:25:42    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.o.app.json.JsonUtil;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.ui.OAlert;
import cn.o.app.ui.OAlert.OAlertListener;
import cn.skinapp.R;

import com.evan.common.adapter.BaseListAdapter;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.net.MRUserDelTask;
import com.smiier.skin.net.MRUserDelTask.MRUserDelRequest;
import com.smiier.skin.net.MRUserDelTask.MRUserDelResponse;
import com.smiier.skin.net.MRUserGetListTask;
import com.smiier.skin.net.MRUserGetListTask.MRUserGetListRequest;
import com.smiier.skin.net.MRUserGetListTask.MRUserGetListResponse;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.umeng.analytics.MobclickAgent;

public class BinglijiaActivity extends BasicActivity implements
		OnRefreshListener<ListView> {

	protected MRUserGetListRequest mRequest = new MRUserGetListRequest();
	PullToRefreshListView list_binglijia;
	BingliAdapter adapter;
	int startuid;
	ArrayList<Object> array = new ArrayList<Object>();
	Button btn_search;

	TextView text_empty;

	View view_filter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_doctor_binglijia);

		init();
		setNavTitle("我的病历夹");
		// setNavRightBtnDrawable(R.drawable.icon_add_bingli);
		setNavRightBtn("+");
		text_right.setTextSize(35);

		text_empty = (TextView) findViewById(R.id.text_empty);
		text_empty.setText("您还没有创建病例");
		list_binglijia = (PullToRefreshListView) findViewById(R.id.list_doctor_binglijia);
		list_binglijia.setOnRefreshListener(this);
		list_binglijia.setPullLoadEnabled(false);
		list_binglijia.setPullRefreshEnabled(false);
		list_binglijia.setScrollLoadEnabled(true);

		mRequest.pagesize = 10;
		mRequest.token = GlobalSettings.sToken;
		mRequest.need_question = GlobalSettings.IS_TRUE;
		list_binglijia.doPullRefreshing(true);
		list_binglijia.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int arg2, long arg3) {
				JSONObject object = (JSONObject) view.getTag();
				Intent intent = new Intent(getContext(),
						BingliDetailActivity.class);
				intent.putExtra(Constant.IDENTITY_KEY, object.toString());
				startActivity(intent);
			}
		});

		list_binglijia.getRefreshableView().setOnItemLongClickListener(
				new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							final View view, final int position, long id) {
						OAlert alert = new OAlert(getContext());
						alert.setOK("确认");
						alert.setCancel("取消");
						alert.setTitle("确认删除这个病历吗？");
						alert.show();
						alert.setListener(new OAlertListener() {

							@Override
							public boolean onOK(OAlert alert) {
								JSONObject object = (JSONObject) view.getTag();
								MRUserDelRequest req = new MRUserDelRequest();
								req.token = GlobalSettings.sToken;
								try {
									req.MRUid = Long.parseLong(object
											.getString("Uid"));
								} catch (JSONException e1) {
									e1.printStackTrace();
								}
								MRUserDelTask task = new MRUserDelTask();
								task.setRequest(req);
								task.addListener(new NetTaskListener<MRUserDelTask.MRUserDelRequest, MRUserDelTask.MRUserDelResponse>() {

									@Override
									public void onException(
											INetTask<MRUserDelRequest, MRUserDelResponse> task,
											Exception e) {
										CommonUtility.tip(getContext(), "删除失败");
									}

									@Override
									public void onComplete(
											INetTask<MRUserDelRequest, MRUserDelResponse> task,
											MRUserDelResponse response) {
										if (response.ResultCode == 200
												&& response.Res == GlobalSettings.IS_TRUE) {
											adapter.removeIndex(position);
											if (adapter.getCount() < 1) {
												text_empty
														.setVisibility(View.VISIBLE);
											}
											toast("删除成功");
										}
									}
								});
								add(task);
								return false;
							}

							@Override
							public boolean onCancel(OAlert alert) {
								return false;
							}
						});
						return true;
					}
				});
		btn_search = (Button) findViewById(R.id.btn_search);
	}

	private void loadData(boolean isShowDialog) {
		mRequest.startuid = startuid;
		mRequest.token = GlobalSettings.sToken;
		MRUserGetListTask task = new MRUserGetListTask();
		task.setRequest(mRequest);
		task.addListener(new NetTaskListener<MRUserGetListTask.MRUserGetListRequest, MRUserGetListTask.MRUserGetListResponse>() {

			@Override
			public void onException(
					INetTask<MRUserGetListRequest, MRUserGetListResponse> task,
					Exception e) {
				list_binglijia.doComplete();
			}

			@Override
			public void onComplete(
					INetTask<MRUserGetListRequest, MRUserGetListResponse> task,
					MRUserGetListResponse response) {
				list_binglijia.doComplete();
				if (response.ResultCode != 200) {
					list_binglijia.setContextEmptyType(true, 2);
					return;
				}
				try {
					JSONArray arr = new JSONArray(JsonUtil
							.convert(response.Res.MRUsers));
					if (arr.length() > 0) {
						CommonUtility.putAll(array, arr, true);
						list_binglijia.setHasMoreData(true);
					} else {
						if (array.size() > 0) {
							list_binglijia.setHasMoreData(false);
						}
					}
					if (array.size() > 0) {
						startuid = ((JSONObject) array.get(array.size() - 1))
								.getInt("Uid");
						text_empty.setVisibility(View.GONE);
					} else {
						text_empty.setVisibility(View.VISIBLE);
					}
					if (CommonUtility.isNull(adapter)) {
						adapter = new BingliAdapter((Activity) getContext(),
								array);
						list_binglijia.setAdapter(adapter);
					} else {
						adapter.notifyUpdate();
					}
					if (array.size() < 1) {
						list_binglijia.setContextEmptyType(true, 2);
					} else {
						list_binglijia.setContextEmptyType(false, 2);
					}
				} catch (Exception e) {
					list_binglijia.setContextEmptyType(true, 2);
					e.printStackTrace();
				}
			}
		});
		add(task);
	}

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.btn_left) {
			finish();
		} else if (id == R.id.text_right) {
			startActivityForResult(
					new Intent(this, CreateBingliActivity.class), 0);
		}
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		startuid = 0;
		array.clear();
		loadData(false);
	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		loadData(false);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == 20) {
			onPullDownToRefresh(null);
		}
	}

	@SuppressLint("InflateParams")
	public static class BingliAdapter extends BaseListAdapter {

		public BingliAdapter(Activity activity, ArrayList<Object> array) {
			super(activity, array);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup root) {

			ViewHolder viewHolder = null;
			if (CommonUtility.isNull(convertView)) {
				viewHolder = new ViewHolder();
				convertView = inflater.inflate(R.layout.item_bingli, null);
				viewHolder.text_patient_name = (TextView) convertView
						.findViewById(R.id.text_patient_name);
				viewHolder.text_sex = (TextView) convertView
						.findViewById(R.id.text_sex);
				viewHolder.text_age = (TextView) convertView
						.findViewById(R.id.text_age);
				viewHolder.text_date = (TextView) convertView
						.findViewById(R.id.text_date);
				viewHolder.text_zhenduan = (TextView) convertView
						.findViewById(R.id.text_zhenduan);
				viewHolder.rl_zhenduan = (RelativeLayout) convertView
						.findViewById(R.id.rl_zhenduan);

				CommonUtility.setViewHolderTag(convertView, viewHolder);
			} else {
				viewHolder = (ViewHolder) CommonUtility
						.getViewHolderTag(convertView);
			}

			try {
				JSONObject object = (JSONObject) getItem(position);
				JSONObject user = object.getJSONObject("User");
				viewHolder.text_patient_name.setText(user.getString("Name"));
				viewHolder.text_sex.setText(CommonUtility.sex.get(user
						.getInt("Sex")));
				viewHolder.text_age.setText(CommonUtility.getAgeByBirthday(user
						.getString("Birth")) + "岁");
				viewHolder.text_date.setText(user.getString("CreateTime")
						.replace("T", Constant.SPACE).substring(5, 16));
				// JSONObject answer = object.getJSONObject("Answer");
				// if (answer.getInt("Qaid") != 0) {
				// viewHolder.rl_zhenduan.setVisibility(View.VISIBLE);
				// viewHolder.text_zhenduan.setText("诊断："
				// + answer.getString("Disease_Inference"));
				// } else {
				// viewHolder.rl_zhenduan.setVisibility(View.GONE);
				// }
				convertView.setTag(object);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}

		class ViewHolder {
			TextView text_patient_name, text_sex, text_age, text_type,
					text_date, text_zhenduan;
			RelativeLayout rl_zhenduan;
		}
	}
	
	
/*	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(getContext());
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(getContext());
	}*/
	
	
}
